<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use think\Db;
use think\Session;
/**
 * 金融类客户管理
 *
 * @icon fa fa-circle-o
 */
class Bkuser extends Backend
{
    
    /**
     * Bkuser模型对象
     * @var \app\admin\model\Bkuser
     */
    protected $model = null;
    protected $admin_data = '';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Bkuser;
        $adminData= Session::get("admin");
        //查询当前admin权限
        $linkAdmin = Db::name('Admin');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name')->alias('a')
            ->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        $this->view->assign("companylistList", $this->model->getCompanylistList());
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("typelistList", $this->model->getTypelistList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加金融类客户
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                Db::startTrans();//开启事务
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    //判断用户是否有效
                    if($params['wechat']||$params['mobile']||$params['email']||$params['qq']){
                        $typelist = '1';
                        $admin_id = session('admin.id');
                        $status = '1';
                    }else{
                        $typelist = '2';
                        $status = '0';
                        //销售专员意外的人随意分配客户
                        if($this->admin_data['gid']!=3){
                            $linkAdmin = Db::name('Admin');
                            $adminData = $linkAdmin->alias('a')->join('fa_auth_group_access c','a.id = c.uid')
                                ->join('fa_auth_group g','c.group_id = g.id','LEFT')
                                ->where(array('g.id'=>array('IN','2,3')))->column('a.id');
                            $admin_id = $adminData[rand(0,count($adminData)-1)];
                        }else{
                            //分配当前销售专员
                            $admin_id = session('admin.id');
                        }
                    }
                    $product_id = explode(',',$params['product_id']);
                    if(!$product_id){
                        $this->error('请选择推广产品');
                    }
                    $add = false;
                    //查询期限时间
                    $linkPlan = Db::name('product');
                    $qi = Db::name('allot_expire')->where(array('id'=>1))->value('expire');
                    $allot_date = date('Y-m-d H:i:s',time());
                    $expire_date = date('Y-m-d H:i:s',strtotime('+'.$qi.' days'));
                    $params['typelist'] = $typelist;
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $linkAllot = Db::name('Allot');
                        foreach ($product_id as $k=>$v){
                            $planData = $linkPlan->where(array('id'=>$v))->find();
                            if($planData){
                                $allotField = array(
                                    'buser_id'=>$this->model->id,
                                    'admin_id'=>$admin_id,
                                    'typelist'=>'1',
                                    'allot_date'=>$allot_date,
                                    'expire_date'=>$expire_date,
                                    'product_id'=>$v,
                                    'status' => $status,
                                    'userlist'=>'2'
                                );
                                $result_allot = $linkAllot->insertGetId($allotField);
                                if($result_allot){
                                    $add = true;
                                }else{
                                    Db::rollback();
                                    $this->error('发配记录失败，请刷新后重试');
                                }
                            }else{
                                Db::rollback();
                                $this->error('推广产品不存在');
                            }
                        }
                        if($add){
                            //操作成功
                            Db::commit();
                            $this->success();
                        }else{
                            Db::rollback();
                            $this->error($this->model->getError());
                        }
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     * $type:方式判断
     */
    public function edit($ids = NULL,$type='')
    {
        if($type==2){
            //分配allot_id
            $linkAllot = Db::name('Allot');
            $allotData = $linkAllot->where(array('id'=>$ids,'userlist'=>'2'))->find();
            if(!$allotData){
                $this->error('不存在当前用户信息');
            }
            $ids = $allotData['buser_id'];

        }
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    //判断用户是否有效
                    if($params['wechat']||$params['mobile']||$params['email']||$params['qq']){
                        $typelist = '1';
                    }else{
                        $typelist = '2';
                    }
                    $params['typelist'] = $typelist;
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
